package cmd

import (
	"context"
	"github.com/gogf/gf/v2/frame/g"
	"github.com/gogf/gf/v2/os/gcmd"
)

var (
	Main = gcmd.Command{
		Name:  "main",
		Usage: "主服务",
		Brief: "主服务",
		Func: func(ctx context.Context, parser *gcmd.Parser) (err error) {
			g.Log().Debug(ctx, "main server")
			// Cron 服务和 http 服务同时运行，可通过http.api进行操作已运行的相关定时任务
			defaultCommands := []*gcmd.Command{Http, Cron} // 默认开启的服务
			for _, cmd := range defaultCommands {
				cmd := cmd
				go func() {
					if err = cmd.Func(ctx, parser); err != nil {
						g.Log().Fatalf(ctx, "child server[%v]start fail: %v", cmd.Name, err)
					}
				}()
			}
			// 监听进程退出的信号
			signalListen(ctx, signalHandlerForOverall)

			//等待所有的子服务关闭后主服务才能关闭
			<-serverCloseSignal
			g.Log().Debug(ctx, "main receive close signal")

			serverWg.Wait()
			g.Log().Debug(ctx, "all child server is closed, main closed")

			return
		},
	}
)

func init() {
	if err := Main.AddCommand(Http, Cron); err != nil {
		panic(err)
	}
}
